package com.dotflat.staffExtend.controller;

import com.alibaba.fastjson.JSON;
import com.dotflat.rest.controller.RestfulBaseController;
import com.dotflat.staffExtend.po.*;
import com.dotflat.staffExtend.domain.StaffExtendInfo;
import com.dotflat.staffExtend.dto.StaffExtendInfoListDTO;
import com.dotflat.staffExtend.repository.StaffExtendInfoRepository;
import com.dotflat.staffExtend.service.StaffExtendInfoService;
import com.dotflat.util.excelUtil.ExcelUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.Classes;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.ClassesRepository;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@RestController
@RequestMapping("/api/staff_extend/info")
@Slf4j
@Api(tags = "员工扩展信息 - 详情")
public class APIStaffExtendInfoController extends RestfulBaseController<StaffExtendInfo, StaffExtendInfoService, StaffExtendInfoPO> {

    @Autowired
    public void setBaseService(StaffExtendInfoService service){
        super.setBaseService(service);
    }

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private StaffExtendInfoRepository infoRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @ApiOperation(value = "获取园区老师档案联合列表", response = StaffExtendInfoListDTO.class)
    @GetMapping("/list_join")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "status", value = "状态", defaultValue = "-1", required = false, dataType = "int"),
    })
    public StatusResponse getList(@RequestHeader(TICKET) String ticket, String realName, String roleId, Integer status ,PagerQuery pagerQuery){
        StaffDTO staff = cache.getStaff(ticket);
        if (Objects.isNull(status)){
            status = -1;
        }
        Map pageMap = ssoCallService.getAreaStaffs(ticket, realName, roleId,status, pagerQuery);

        //这里是因为无法自动转PageImpl
        List<Map<String, String>> content = (List) pageMap.get("content");
        if (content == null || content.size() == 0) {
            StatusResponse.success(pageMap);
        }

        List<String> staffIds = content.stream().map(o->(String)o.get("id")).collect(Collectors.toList());

        //处理扩展信息
//        List<String> staffIds = staffs.stream().map(StaffExtendInfoListDTO::getStaffId).collect(Collectors.toList());
        List<StaffExtendInfo> extendInfos = infoRepository.findAllByAreaIdAndStaffIdIn(staff.getAreaId(), staffIds);
        Map<String, StaffExtendInfo> cache = extendInfos.stream().collect(Collectors.toMap(StaffExtendInfo::getStaffId, o->o));

        content.stream().forEach(o->{
            String staffId = o.get("id");
            StaffExtendInfo info = cache.get(staffId);
            if (info != null) {
                o.put("extendInfoId",info.getId());
                o.put("position",info.getPosition());
                if (info.getBirthday() != null)
                    o.put("birthday", DateUtil.formatDayToStr(info.getBirthday()));
                if (info.getJoinAt() != null)
                    o.put("joinAt", DateUtil.formatDayToStr(info.getJoinAt()));
                if (info.getResignDate() != null)
                    o.put("resignDate", DateUtil.formatDayToStr(info.getResignDate()));
            }

            //TODO：这里需要修改
            String mobile = o.get("mobile");
            // 安全处理手机号最后一位字符
            char lastChar = mobile.charAt(mobile.length() - 1);
            int digitValue;

            // 对数字字符安全转换，非数字字符用默认值替代
            if (Character.isDigit(lastChar)) {
                digitValue = Character.getNumericValue(lastChar);
            } else {
                // 非数字字符处理（这里用0替代，也可改为其他逻辑）
                digitValue = 0;
            }

            o.put("rankVal", (digitValue % 6) + "");
        });

        //处理评分信息
        //TODO:需要变更评分逻辑

        return StatusResponse.success(pageMap);
    }

    @ApiOperation(value = "增加一条记录")
    @PostMapping()
    @Override
    public StatusResponse add(@RequestHeader(TICKET) String ticket, StaffExtendInfoPO param){
        StaffDTO staff = cache.getStaff(ticket);

        String id = param.getStaffId();

        StaffDTO newStaff = null;
        if (StringUtils.isBlank(id)){
            //新建一个用户
            newStaff = new StaffDTO();
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(staff.getAreaId());

            if (StringUtils.isNotEmpty(param.getRoleId())){
                newStaff = ssoCallService.createStaff(ticket, newStaff, new String[]{param.getRoleId()});
            }else{
                newStaff = ssoCallService.createStaff(ticket, newStaff);
            }

            return StatusResponse.success(newStaff);
        }else{
            newStaff = new StaffDTO();

            newStaff.setId(id);
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(staff.getAreaId());

            newStaff = ssoCallService.updateStaff(ticket, newStaff);
        }

        if (newStaff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "指定员工不存在");
        }

        param.setStaffId(newStaff.getId());

        //找到是否存在对应的档案
        StaffExtendInfo exist = infoRepository.findFirstByAreaIdAndStaffId(staff.getAreaId(), newStaff.getId());
        if (exist != null){
            param.setId(exist.getId());
        }

        StaffExtendInfo ret = baseService.add(staff.getAreaId(), staff.getId(), param);

        return StatusResponse.success(ret);
    }


    @ApiOperation(value = "增加一条记录")
    @PostMapping("add2")
    public StatusResponse add2(@RequestHeader(TICKET) String ticket, StaffExtendInfoPO2 param){
        if (null!=param.getContactInformation()) {
            param.setMobile(param.getContactInformation());
        }
        StaffDTO staff = cache.getStaff(ticket);

        List<String> roles = new LinkedList<>();//存储角色信息
        if(null!=param.getStaffChildPOList4() && param.getStaffChildPOList4().size()>0){
            //不能选择重复的岗位
            // 提取所有positionHeld值，过滤掉null值
            List<String> positionHeldList = param.getStaffChildPOList4().stream()
                    .map(StaffChildPO::getPositionHeld)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if (positionHeldList.size() != new HashSet<>(positionHeldList).size()) {
                throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "不能选择重复的岗位");
            }

            for (StaffChildPO staffChildPO : param.getStaffChildPOList4()) {
                if(null!=staffChildPO.getPositionHeld() && !staffChildPO.getPositionHeld().equals("")){
                    roles.add(staffChildPO.getPositionHeld());
                }

                //查询班级名称
                if(null!=staffChildPO.getClassesId() && !staffChildPO.getClassesId().equals("")){
                    Classes one = classesRepository.getOne(staffChildPO.getClassesId());
                    if(null!=one && null!=one.getName()){
                        staffChildPO.setClassesName(one.getName());
                    }
                }
            }
        }
        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
        if(null!=param.getStaffChildPOList3() && param.getStaffChildPOList3().size()>0){
            for (StaffChildPO staffChildPO : param.getStaffChildPOList3()) {
                if(null!=staffChildPO.getStartStopTime() && staffChildPO.getStartStopTime().size()>0){
                    try {
                        staffChildPO.setStartTime(fmt.parse(staffChildPO.getStartStopTime().get(0)));
                        staffChildPO.setStopTime(fmt.parse(staffChildPO.getStartStopTime().get(1)));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        String id = param.getStaffId();
        param.setId(null);
        String paramJson = JSON.toJSONString(param);

        StaffDTO newStaff = null;
        if (StringUtils.isBlank(id)){
            //新建一个用户
            newStaff = new StaffDTO();
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(staff.getAreaId());

            newStaff = ssoCallService.createStaff2(ticket, newStaff,roles,paramJson);
        }else{
            newStaff = new StaffDTO();

            newStaff.setId(id);
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(staff.getAreaId());

            newStaff = ssoCallService.updateStaff2(ticket, newStaff,roles,paramJson);
        }

        if (newStaff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "指定员工不存在");
        }

        param.setStaffId(newStaff.getId());

        //找到是否存在对应的档案
        StaffExtendInfo exist = infoRepository.findFirstByAreaIdAndStaffId(staff.getAreaId(), newStaff.getId());
        if (exist != null){
            param.setId(exist.getId());
        }

        StaffExtendInfo ret = baseService.add(staff.getAreaId(), staff.getId(), param);

        return StatusResponse.success(ret);
    }






    @ApiOperation(value = "增加一条记录")
    @PostMapping("add3")
    public StatusResponse add3(String ticket, StaffExtendInfoPO2 param){
        if (null!=param.getContactInformation()) {
            param.setMobile(param.getContactInformation());
        }
        StaffDTO staff = cache.getStaff(ticket);

        List<String> roles = new LinkedList<>();//存储角色信息
        if(null!=param.getStaffChildPOList4() && param.getStaffChildPOList4().size()>0){
            for (StaffChildPO staffChildPO : param.getStaffChildPOList4()) {
                if(null!=staffChildPO.getPositionHeld() && !staffChildPO.getPositionHeld().equals("")){
                    roles.add(staffChildPO.getPositionHeld());
                }

                //查询班级名称
                if(null!=staffChildPO.getClassesId() && !staffChildPO.getClassesId().equals("")){
                    Classes one = classesRepository.getOne(staffChildPO.getClassesId());
                    if(null!=one && null!=one.getName()){
                        staffChildPO.setClassesName(one.getName());
                    }
                }
            }
        }
        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
        if(null!=param.getStaffChildPOList3() && param.getStaffChildPOList3().size()>0){
            for (StaffChildPO staffChildPO : param.getStaffChildPOList3()) {
                if(null!=staffChildPO.getStartStopTime() && staffChildPO.getStartStopTime().size()>0){
                    try {
                        staffChildPO.setStartTime(fmt.parse(staffChildPO.getStartStopTime().get(0)));
                        staffChildPO.setStopTime(fmt.parse(staffChildPO.getStartStopTime().get(1)));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        String id = param.getStaffId();
        param.setId(null);
        String paramJson = JSON.toJSONString(param);

        StaffDTO newStaff = null;
        if (StringUtils.isBlank(id)){
            //新建一个用户
            newStaff = new StaffDTO();
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(staff.getAreaId());

            newStaff = ssoCallService.createStaff2(ticket, newStaff,roles,paramJson);
        }else{
            newStaff = new StaffDTO();

            newStaff.setId(id);
            newStaff.setGender(param.getGender());
            newStaff.setRealName(param.getRealName());
            newStaff.setHeadImgUrl(param.getHeadImgUrl());
            newStaff.setMobile(param.getMobile());
            newStaff.setLastLogin(0L);
            newStaff.setAreaId(staff.getAreaId());

            newStaff = ssoCallService.updateStaff2(ticket, newStaff,roles,paramJson);
        }

        if (newStaff == null){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "指定员工不存在");
        }

        param.setStaffId(newStaff.getId());

        //找到是否存在对应的档案
        StaffExtendInfo exist = infoRepository.findFirstByAreaIdAndStaffId(staff.getAreaId(), newStaff.getId());
        if (exist != null){
            param.setId(exist.getId());
        }

        StaffExtendInfo ret = baseService.add(staff.getAreaId(), staff.getId(), param);

        return StatusResponse.success(ret);
    }





    @ApiOperation(value = "修改用户个人资料")
    @PostMapping("updateUser")
    public StatusResponse updateUser(String ticket, StaffExtendInfoPO2 param){
        String id = param.getStaffId();
        param.setId(id);
        String paramJson = JSON.toJSONString(param);

        ssoCallService.updateStaff3(ticket,paramJson);
        return StatusResponse.success();
    }





    @ApiOperation(value = "绩效评估列表查询",httpMethod = "POST")
    @RequestMapping("/performanceList")
    public StatusResponse performanceList(@RequestHeader(TICKET)String ticket,@RequestBody PerformanceQueryPO performanceQueryPO) {

        Map pageMap = ssoCallService.performanceList(ticket, performanceQueryPO);

        return StatusResponse.success(pageMap);
    }

    @ApiOperation(value = "新增或编辑绩效评估",httpMethod = "POST")
    @RequestMapping("/saveOrUpdatePerformance")
    public StatusResponse saveOrUpdatePerformance(@RequestHeader(TICKET)String ticket,@RequestBody PerformanceDetailPO performanceDetailPO) {

        return ssoCallService.saveOrUpdatePerformance(ticket,performanceDetailPO);
    }


    @ApiOperation(value = "绩效评估详情",httpMethod = "POST")
    @RequestMapping("/detail")
    public StatusResponse detail(@RequestBody PerformanceQueryPO performanceQueryPO) {

        return StatusResponse.success(ssoCallService.detail(performanceQueryPO));
    }


    @ApiOperation(value = "考勤管理导出 ",httpMethod = "POST")
    @GetMapping("/exportPerformance")
    public void exportClassCheckDetail(HttpServletResponse response,@RequestHeader(TICKET)String ticket,PerformanceQueryPO performanceQueryPO) throws IOException {
        List<PerformanceExcelPO> excelPOList = ssoCallService.exportPerformance(response, ticket, performanceQueryPO);

        ExcelUtil<PerformanceExcelPO> excelUtil = new ExcelUtil<PerformanceExcelPO>(PerformanceExcelPO.class);
        excelUtil.exportExcel(response,excelPOList,"师资绩效评估导出","师资绩效评估导出");
    }


    @ApiOperation(value = "绩效评估删除",httpMethod = "GET")
    @GetMapping("/remove")
    public StatusResponse remove(String id) {

        return StatusResponse.success(ssoCallService.remove(id));
    }

}
